package com.bw.gmall.realtime.dim.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.TableProcessDim;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.FlinkSourceUtil;
import com.bw.gmall.realtime.common.util.HbaseUtil;
import com.bw.gmall.realtime.dim.functions.DimBroadcastFunction;
import com.bw.gmall.realtime.dim.functions.DimSinkFunction;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class DimApp extends BaseApp {
    public static void main(String[] args) {
        new DimApp().start(10001,4,Constant.TOPIC_DB,"dim_app");
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaSource) {
        // 1.读取Kafka的数据，做数据清洗
        //kafkaSource.filter().map()
        SingleOutputStreamOperator<JSONObject> kafkaStream = etl(kafkaSource);
//        kafkaStream.print();
        // 2、通过CDC读取维度配置表，
        DataStreamSource<String> mysqlStream = env.fromSource(FlinkSourceUtil.getMysqlSource(Constant.PROCESS_DATABASE,Constant.PROCESS_DIM_TABLE_NAME), WatermarkStrategy.noWatermarks(), "mysql_source").setParallelism(1);
        // 3、先在Hbase表，用Hbase原生语法
        SingleOutputStreamOperator<TableProcessDim> createTableStream = createTable(mysqlStream);
        // createTableStream.print();
        // 4、将主流和广播流，合并，分流处理
        MapStateDescriptor<String,TableProcessDim> stateDescriptor = new MapStateDescriptor<String, TableProcessDim>("broadcast_state",String.class,TableProcessDim.class);
        BroadcastStream<TableProcessDim> broadcastStream = createTableStream.broadcast(stateDescriptor);
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> processStream = connect(kafkaStream, broadcastStream,stateDescriptor);
//        processStream.print();
//         5、过滤字段，写入Hbase
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> filterStream = filterColums(processStream);
//        filterColumStream.print();
        // 6、写出数据
        filterStream.addSink(new DimSinkFunction());

    }

    private SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> filterColums(SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> processStream) {
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> filterColumStream = processStream.map(new MapFunction<Tuple2<JSONObject, TableProcessDim>, Tuple2<JSONObject, TableProcessDim>>() {
            @Override
            public Tuple2<JSONObject, TableProcessDim> map(Tuple2<JSONObject, TableProcessDim> processDimTuple2) throws Exception {
                JSONObject f0 = processDimTuple2.f0;
                TableProcessDim f1 = processDimTuple2.f1;
                String sinkColumns = f1.getSinkColumns();
                List<String> columns = Arrays.asList(sinkColumns.split(","));
                // 主流的data数据
                JSONObject data = f0.getJSONObject("data");
                // 删除不要的数据
                data.keySet().removeIf(key -> !columns.contains(key));

                return processDimTuple2;
            }
        });
        return filterColumStream;
    }

    private SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> connect(SingleOutputStreamOperator<JSONObject> kafkaStream, BroadcastStream<TableProcessDim> broadcastStream, MapStateDescriptor<String,TableProcessDim> stateDescriptor) {
        return kafkaStream.connect(broadcastStream).process(new DimBroadcastFunction(stateDescriptor));
    }

    private SingleOutputStreamOperator<TableProcessDim> createTable(DataStreamSource<String> mysqlStream) {
        SingleOutputStreamOperator<TableProcessDim> createTableStream = mysqlStream.flatMap(new RichFlatMapFunction<String, TableProcessDim>() {

            private Connection hbaseConnect;// ctrl+alt+f

            @Override
            public void open(Configuration parameters) throws Exception {
                hbaseConnect = HbaseUtil.getHbaseConnect();
            }

            @Override
            public void flatMap(String s, Collector<TableProcessDim> collector) throws Exception {
                TableProcessDim dim;
                // 1. 转成jsonobject
                JSONObject jsonObject = JSON.parseObject(s);
                // c r u d
                String op = jsonObject.getString("op");
                if ("d".equals(op)) {
                    // 删除
                    dim = jsonObject.getObject("before", TableProcessDim.class);
                    deleteTable(dim);
                } else if ("c".equals(op) || "r".equals(op)) {
                    // 创建和读
                    dim = jsonObject.getObject("after", TableProcessDim.class);
                    String sinkFamily = dim.getSinkFamily();
                    String[] split = sinkFamily.split(",");
                    HbaseUtil.createHBaseTable(hbaseConnect, Constant.HBASE_NAMESPACE, dim.getSinkTable(), split);
                } else {
                    // 更新
                    dim = jsonObject.getObject("after", TableProcessDim.class);
                    deleteTable(dim);
                    createTable(dim);
                }
                dim.setOp(op);
                collector.collect(dim);
            }

            private void createTable(TableProcessDim dim) throws IOException {
                HbaseUtil.createHBaseTable(hbaseConnect, Constant.HBASE_NAMESPACE, dim.getSinkTable());
            }

            private void deleteTable(TableProcessDim dim) throws IOException {
                HbaseUtil.dropHBaseTable(hbaseConnect, Constant.HBASE_NAMESPACE, dim.getSinkTable());
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeHBaseConn(hbaseConnect);
            }
            // 并行度设置1
        }).setParallelism(1);
        return createTableStream;
    }

    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> kafkaSource) {
        SingleOutputStreamOperator<JSONObject> kafkaStream = kafkaSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(s);
                    String db = jsonObject.getString("database");
                    String type = jsonObject.getString("type");
                    String data = jsonObject.getString("data");
//                    if ("gmall".equals(db)
//                            && "insert".equals(type)
//                            || "update".equals(type)
//                            || "delete".equals(type)
//                            || "bootstrap-insert".equals(type) && data != null && data.length() > 2) {
//                        collector.collect(jsonObject);
//                    }
                    if ("gmall".equals(db) && !"bootstrap-start".equals(type) && !"bootstrap-complete".equals(type) && data != null && data.length() > 0){
                        collector.collect(jsonObject);
                    }

                } catch (Exception e) {
                    log.error("出现异常数据");
                }

            }
        });
        return kafkaStream;
    }


}
